import { asyncComputed, createInjectionState } from '@peng_kai/kit/libs/vueuse';
import { getGameInfo, useGameInfoQuery } from '../helpers';
import { useOnGamePM } from './helpers';
import type { TSvStatus } from '~comp/suspense';
import { useLocale } from '~/modules/locale';
import { getCookieValue } from '~/utils';

export const [useProvideGameStore, useGameStore] = createInjectionState (() => {
  const myGameLog = useGmaeLog('addMyLog');
  const allGameLog = useGmaeLog('addAllLog');
  const { isDev, gameCode, gameUrl } = useGameConfig();
  // const gameDetail = asyncComputed(() => gameCode.value ? getGameInfo(gameCode.value) : undefined);
  const { gameInfoQry, gameInfo } = useGameInfoQuery(gameCode);

  return { myGameLog, allGameLog, isDev, gameCode, gameUrl, gameDetail: gameInfo };
});

function useGameConfig() {
  const { currentRoute } = useRouter();
  const appStore = useAppStore();
  const { locale } = useLocale();
  const isAuthed = useAuthed();

  const isDev = computed(() => {
    const route = currentRoute.value;
    const gameCode = String(route.params.gameCode);
    return import.meta.env.DEV && gameCode === 'dev' && typeof route.query.url === 'string';
  });
  const gameCodeFromUrl = computed(() => String(currentRoute.value.params.gameCode));
  const config = ref<any>();
  const gameCodeFromIframe = computed(() => config.value?.game.code);
  const gameCode = computed(() => isDev.value ? gameCodeFromIframe.value : gameCodeFromUrl.value);
  const gameUrl = computed(() => {
    const route = currentRoute.value;
    const gameDomain = appStore.handshake?.domain.game.replace(/\/$/, '');

    try {
      const url = new URL(isDev.value ? String(route.query.url) : `${gameDomain}/${gameCodeFromUrl.value}`);
      isAuthed.value && url.searchParams.set('token', getCookieValue('token'));
      url.searchParams.set('locale', locale.value);
      return url.toString();
    }
    catch {
      return '';
    }
  });

  useOnGamePM('loaded', (data) => {
    config.value ??= data;
  });

  return { isDev, gameCode, gameUrl };
}

function useGmaeLog(pmName: 'addMyLog' | 'addAllLog') {
  interface TLog {
    betAmount: string;
    profitAmount: string;
    rewardAmount: string;
    currency: string;
    multiplier: number;
    id: string;
    prizeStatus: number;
    time: number;
    user?: {
      level: number;
      uid: string;
      nickname: string;
      avatar: string;
    };
  }

  const MAX_LAN = 50;
  const pageSize = ref(10);
  const status = ref<TSvStatus>('pending');
  const list = ref<TLog[]>([]);
  const listSliced = computed(() => list.value.slice(0, pageSize.value));

  const add = (log: TLog) => {
    if (!log.time)
      return;

    const index = list.value.findIndex(item => item.id === log.id);

    if (index > -1) {
      // 如果日志已存在，则本次添加算作更新日志状态
      list.value[index] = log;
    }
    else {
      list.value = [log, ...list.value].sort((a, b) => b.time - a.time).slice(0, MAX_LAN);
    }
  };

  useOnGamePM(pmName, add);
  useOnGamePM('loaded', async () => {
    await sleep(1000);
    status.value = list.value.length ? 'success' : 'empty';
  });

  return reactive({ list: listSliced, pageSize, status, add });
}
